package ch.elca.training.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import ch.elca.training.dto.ProjectCriterionDto;
import ch.elca.training.model.UrlConstants;
import ch.elca.training.service.ProjectService;
import ch.elca.training.validator.ProjectCriterionValidator;

@Controller
@RequestMapping(UrlConstants.SEARCH)
@SessionAttributes("criterion")
public class SearchProjectsController {

	public static final String COMMAND_OBJECT_NAME = "criterion";
	
	@Autowired
	private ProjectService projectService;
	
	@Autowired
	private ProjectCriterionValidator projectCriterionValidator;
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.setValidator(projectCriterionValidator);
	}
	
	@RequestMapping(method = RequestMethod.GET)
    protected String showForm(Model model) {
    	if (!model.containsAttribute(COMMAND_OBJECT_NAME)) {
    		model.addAttribute(COMMAND_OBJECT_NAME, new ProjectCriterionDto());
    	}
        return UrlConstants.SEARCH;
    }
	
	@RequestMapping(method = RequestMethod.POST)
	public String onSubmit(@ModelAttribute(COMMAND_OBJECT_NAME) @Valid ProjectCriterionDto criterion, BindingResult result){
		if(result.hasErrors()) {
			return UrlConstants.SEARCH;
		} else {
			return UrlConstants.REDIRECT_PREFIX
					+ UrlConstants.SEARCH;
		}
	}
	
	
}
